<?php
/*
 * @Author: your name
 * @Date: 2020-06-06 13:32:49
 * @LastEditTime: 2020-06-07 13:06:30
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \hotel\application\api\controller\Index.php
 */
namespace app\api\controller;

use think\Controller;
use think\Db;

error_reporting(0);
// 制定允许其他域名访问
header("Access-Control-Allow-Origin:*");
// 允许的响应类型
header('Access-Control-Allow-Methods: GET, POST, PUT,DELETE,OPTIONS,PATCH');
// 响应头设置
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");
class Index extends Controller
{   
    
    //首页
    public function index()
    {

        $user_id = session("user_id");
        
        if (empty($user_id)) {
            header('Location: /mobile/login.html?v=1');exit;
        } else {
            header('Location: /mobile/index.html?v=1');exit;
        }

    }

    
    //获取所有除了新人券和活动券和生日券优惠券
    private function couponall()
    {
        $coupon = db('coupon')
            ->alias('a')
            ->join('think_coupon_cate b', 'a.cate_id=b.id', 'left')
            ->where(['a.status' => 0, 'a.automatic' => 1, 'a.buy_money' => 0, 'a.is_activity' => 0])
            ->where("b.id!=1 and b.id!=2")
            ->where("a.number>0")
            ->field('a.id,a.title,a.money,a.full_money,a.end_time,b.title as cate_title')
            ->select();
        return $coupon;
    }

    //获取新人券
    private function newperson()
    {
        $coupon = db('coupon')
            ->alias('a')
            ->join('think_coupon_cate b', 'a.cate_id=b.id', 'left')
            ->where(['a.status' => 0, 'a.automatic' => 1, 'a.buy_money' => 0, 'a.is_activity' => 0, 'b.status' => 0, 'b.id' => 1])
            ->where("a.number>0")
            ->field('a.id,a.title,a.money,a.full_money,a.end_time,b.title as cate_title')
            ->select();
        return $coupon;
    }
    
    //首页接口
    public function newIndex()
    {   
        $user_id = session('user_id');
        if (empty($user_id)) {
            return json(['code' => -1, 'msg'=>'请登录']);
        } else {
            
            $user=db("user")->where(['user_id'=>$user_id])->find();
            
            if(empty($user)){
                
                session("user_id",null); 
               
                return json(['code' => -1, 'msg'=>'请登录']);
            }
            if($user['user_status']==1){ 
                
                return json(['code' => -1, 'msg'=>'请登录']);
            }
        }
        
        //会员卡编号操作
        vipnumber($user_id);
        
        //优惠券列表
        $allcoupon = $this->couponall();
        
        $newperson = $this->newperson();
        //查找用户是不是第一次进来
        $login_num = db('user')->where(['user_id' => $user_id])->value('login_num');
        
        if ($login_num == 1) {
            db('user')->where(['user_id' => $user_id])->setInc('login_num');
            //清空用户的优惠券
            db('coupon_user')->where(['user_id' => $user_id])->delete();
            $couponlist = array_merge($newperson, $allcoupon);

        } else { 
            //查询用户的优惠券
            $user_coupon_id = db('coupon_user')->where(['user_id'=>$user_id])->column('coupon_id');
           
            $array_coupon_id=array_column($allcoupon,'id');
            $need_coupon_id_id = array_diff($array_coupon_id,$user_coupon_id);
            
            foreach ($need_coupon_id_id as &$v){
               
                $couponlist[] = db('coupon')
                    ->alias('a')
                    ->join('think_coupon_cate b', 'a.cate_id=b.id', 'left')
                    ->where(['a.id' => $v]) 
                    ->field('a.id,a.title,a.money,a.full_money,a.end_time,b.title as cate_title')
                    ->find();
            }
            
        }
        
        //banner图
        $banner = db('banner')
            ->where(['status' => 0])
            ->order('id desc,list_order desc')
            ->field('id,img,link,list_order')
            ->select();
        
        //获取用户的经纬度
        $userLocation = userlocation();
        
        //获取酒店的信息
        $hotel = db('hotel')->field('address,start_time,end_time,lng,lat')->find(1);
        
        //活动
        $activity = db('activity')
            ->where(['status'=>0])
            ->where("end_time<".time())
            ->field('id,title')
            ->select();
            
            
        $couponlist = $couponlist?:[];
        
        return json([
            'code' => 1, 
            'msg' => '查询成功', 
            'data' => ['banner' => $banner, 'couponlist' => $couponlist, 'hotel' => $hotel,'userlocation'=>$userLocation,'activity'=>$activity]]);
    }

    
    //领取优惠券--id为数组
    public function receive(){
        
        $id = input('post.id');
        $id = explode(',',$id);
         
        foreach($id as &$v){
            //减少优惠券的数量
            $coupon = db('coupon')->where(['id'=>$v])->find();
            if($coupon['number']>0){
                db('coupon')->where(['id'=>$v])->setDec('number',1);
                $coupon = db('coupon')->find($v);
                if($coupon['end_time']==0){
                    $endtime = 0;
                }else{
                    $endtime = time()+$coupon['end_time']*24*3600;
                }
                $data[] = [
                    'user_id' => session('user_id'),
                    'coupon_id' => $v,
                    'status' => 0,
                    'coupon_info' => serialize($coupon),
                    'create_time' => time(),
                    'end_time' => $endtime,
                ];
            }
            
        }
        $res = db('coupon_user')->insertAll($data);
        
        if($res){
            return json(['code' => 1, 'msg' => '领取成功']);
        }else{
            return json(['code' => 0, 'msg' => '领取失败']);
        }
        
    }
    
    
    //优惠券列表---新人的手动的生日的活动的次数不足状态下架的用户已经领取不展示
    public function couponlist(){
        
        $user_id = session('user_id');
        if (empty($user_id)) {
            return json(['code' => -1, 'msg'=>'请登录']);
        } else {
            $user = db('user')->where(['user_id' => $user_id])->field('login_num,user_status')->find();
            if ($user['user_status'] == 1) {
                return json(['code' => 0, 'msg'=>'账号被禁用']);
            }
        }
        
        $array_coupon_id = db('coupon')
            ->alias('a')
            ->join('think_coupon_cate b', 'a.cate_id=b.id', 'left')
            ->where(['a.status' => 0, 'a.automatic' => 1, 'a.buy_money' => 0, 'a.is_activity' => 0, 'b.status' => 0])
            ->where("b.id!=1 and b.id!=2")
            ->where("a.number=-1 or a.number>0") 
            ->column('a.id');
        
        //查询用户的优惠券
        $user_coupon_id = db('coupon_user')->where(['user_id'=>$user_id])->column('coupon_id');
        
        $need_coupon_id_id = array_diff($array_coupon_id,$user_coupon_id); 
        $couponlistld = implode(',',$need_coupon_id_id);
        $couponlist = db('coupon')
            ->where(['id'=>['in',$couponlistld]])
            ->field('id,title,money,full_money,start_time,end_time,number,use_rule,cate_id')
            ->select();
        foreach ($couponlist as $i => $item) {
            $couponlist[$i]['cate'] = db('coupon_cate')->where(['id'=>$item['cate_id']])->find()['title'];
            $couponlist[$i]['start_time'] = date('Y-m-d H:i:s',$item['start_time']);
        }
        return json(['code' => 1, 'msg'=>'查询成功','data'=>$couponlist]);
    }
    
    
    
    // 发送短信验证
    public function setpaypwdcode()
    {
        $user_id =  session('user_id');
        if (empty($user_id)) {
            return json(['code' => -1, 'msg'=>'请登录']);
        } else {
            $user = db('user')->where(['user_id' => $user_id])->field('login_num,user_status,phone')->find();
            if ($user['user_status'] == 1) {
                return json(['code' => 0, 'msg'=>'账号被禁用']);
            }
        }
        $mobile = $user['phone'];
        if (!trim($mobile)) {
            return json(['code' => 0, 'msg' => '暂未绑定手机号']);
        }
        
        $check = db("user")->where(['phone' => $mobile])->find();
        
        if (!$check) {
            return json(['code' => 0, 'msg' => '该手机号码不存在']);
        }
        
        $auth = db("mobile")->where(['mobile' => $mobile])->find();

        if (time() - $auth['sendtime'] < 60) {
            return json(['code' => 0, 'msg' => '请不要重复发送']);
        }
        $result = $this->send_code($mobile);
        if ($result['code']==1) {
            return json(['code' => 1, 'msg' => '发送成功']);
        }
        return json(['code' => 0, 'msg' => '发送失败']);
    }
    // 重置密码
    public function forgetpaypwd()
    {
        $user_id = session('user_id');
        if (empty($user_id)) {
            return json(['code' => -1, 'msg'=>'请登录']);
        } else {
            $user = db('user')->where(['user_id' => $user_id])->field('login_num,user_status,phone')->find();
            if ($user['user_status'] == 1) {
                return json(['code' => 0, 'msg'=>'账号被禁用']);
            }
        }
        $code = input('code');
        $paypwd = input('paypwd');
        if (!trim($code)) {
            return json(['code' => 0, 'msg' => '请输入验证码']);
        }
        $verify = $this->verify_code($user['phone'],$code);
        if (!empty($verify)) {
            return json($verify);
        }
        if(!isset($paypwd)){
            return json(['code' => 0, 'msg' => '请输入新密码']);
        }
        $leng = strlen($paypwd);
        if($leng != 6){
            return json(['code'=>0,'msg'=>'密码长度为6位']);
        }
        if(!preg_match('/^[A-Za-z0-9]+$/i',$paypwd)){
            return json(['code'=>0,'msg'=>'密码必须为字母与数字组合使用']);
        }
        $paypwd = md5($paypwd);
        $list = db('user')->where(['user_id'=>$user_id])->update(['paypwd'=>$paypwd]);
        if($list){
            return json(['code'=>1,'msg'=>'支付密码更换成功']);
        }else{
            return json(['code'=>1,'msg'=>'系统繁忙']);
        }  

    }
    //更换手机号
    public function changephone()
    {   
        $user_id = session('user_id');
        // $user_id = $this->user_id;
        if (empty($user_id)) {
            return json(['code' => -1, 'msg'=>'请登录']);
        } else {
            $user = db('user')->where(['user_id' => $user_id])->field('login_num,user_status')->find();
            if ($user['user_status'] == 1) {
                return json(['code' => 0, 'msg'=>'账号被禁用']);
            }
        }
        
        $mobile = input('mobile');
        $code = input('code');
        $old_phone = input('old_phone');
        if (!trim($mobile)) {
            return json(['code' => 0, 'msg' => '请输入新手机号码']);
        }
        if (!trim($old_phone)) {
            return json(['code' => 0, 'msg' => '请输入旧手机号码']);
        }
        $user = db('user')->where(['user_id'=>$user_id,'phone'=>$old_phone])->find();
        if(!$user){
            return json(['code'=>0,'msg'=>'原手机号不匹配']);
        }
        if (!trim($code)) {
            return json(['code' => 0, 'msg' => '请输入验证码']);
        }
        $verify = $this->verify_code($mobile, $code);
        if (!empty($verify)) {
            return json($verify);
        }
        
        $res = db('user')->where(['user_id'=>$user_id])->update(['phone' => $mobile]);
        
        if ($res) {
            return json(['code' => 1, 'msg' => '绑定成功']);
        }else{
            return json(['code' => 0, 'msg' => '绑定失败']);
        }
         
    }
    /**验证短信
     * @param $mobile
     * @param $code
     * @return bool
     */
    public function verify_code($mobile, $code)
    {
        $auth = db("mobile")->where(['mobile' => $mobile])->find();
        if ($auth['sendtime'] + $auth['validtime'] < time()) {
            return ['code' => 0, 'msg' => '验证码已过期,请重新获取'];
        }
        if ($auth['code'] != $code) {
            return ['code' => 0, 'msg' => '验证码错误'];
        }
        return false;
    }
    //发送验证码
    public function getCode()
    {
        $user_id =  $user_id = session("user_id");
        if (empty($user_id)) {
            return json(['code' => -1, 'msg'=>'请登录']);
        } else {
            $user = db('user')->where(['user_id' => $user_id])->field('login_num,user_status')->find();
            if ($user['user_status'] == 1) {
                return json(['code' => 0, 'msg'=>'账号被禁用']);
            }
        }
        $mobile = input('mobile');
        if (!trim($mobile)) {
            return json(['code' => 0, 'msg' => '请输入手机号码']);
        }
        
        $check = db("user")->where(['phone' => $mobile])->find();
        
        if ($check) {
            return json(['code' => 0, 'msg' => '该手机号码已存在']);
        }
        
        $auth = db("mobile")->where(['mobile' => $mobile])->find();

        if (time() - $auth['sendtime'] < 60) {
            return json(['code' => 0, 'msg' => '请不要重复发送']);
        }
        $result = $this->send_code($mobile);
        if ($result['code']==1) {
            return json(['code' => 1, 'msg' => '发送成功']);
        }
        return json(['code' => 0, 'msg' => '发送失败']);
    }
    
    //登录接口
    public function login()
    {   
        $user_id = session('user_id');
        // $user_id = $this->user_id;
        if (empty($user_id)) {
            return json(['code' => -1, 'msg'=>'请登录']);
        } else {
            $user = db('user')->where(['user_id' => $user_id])->field('login_num,user_status')->find();
            if ($user['user_status'] == 1) {
                return json(['code' => 0, 'msg'=>'账号被禁用']);
            }
        }
        
        $mobile = input('mobile');
        $code = input('code');
        if (!trim($mobile)) {
            return json(['code' => 0, 'msg' => '请输入手机号码']);
        }
        if (!trim($code)) {
            return json(['code' => 0, 'msg' => '请输入验证码']);
        }
        $verify = $this->verify_code($mobile, $code);
        if (!empty($verify)) {
            return json($verify);
        }
        
        $res = db('user')->where(['user_id'=>$user_id])->update(['phone' => $mobile]);
        
        if ($res) {
            return json(['code' => 1, 'msg' => '绑定成功']);
        }else{
            return json(['code' => 0, 'msg' => '绑定失败']);
        }
         
    }
    /**
     * 发送验证码
     */
    public function send_code($mobile)
    {
        $time = time();
        //短信接口
        header("Content-type: text/html; charset=utf-8");
        date_default_timezone_set('PRC'); //设置默认时区为北京时间
        //短信接口用户名 $uid
        $uid = 'XAJS003593';
        //短信接口密码 $passwd
        $passwd = '1234567@';

        //短信 --验证码
        $code = rand(100000, 999999);
        $massage = "您的验证码是" . $code.【禅寓酒店】;
        // $msg = rawurlencode(mb_convert_encoding($massage, "gb2312", "utf-8"));

        $url = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx?";

        $ContentS = rawurlencode(mb_convert_encoding($massage, "gb2312", "utf-8")); //短信内容做GB2312转码处理
        $curpost = "CorpID=" . $uid . "&Pwd=" . $passwd . "&Mobile=" . $mobile . "&Content=" . $ContentS . "&SendTime=";

        //GET方式请求
        $ch = curl_init();
        //curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查 -https
        //curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($ch, CURLOPT_URL, $url . $curpost);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $result = curl_exec($ch);
        curl_close($ch);
        $result = file_get_contents($url . $curpost);
        

        // $gateway = "https://sdk2.028lk.com/sdk2/BatchSend2.aspx?CorpID={$uid}&Pwd={$passwd}&Mobile={$mobile}&Content={$msg}&Cell=&SendTime=";
        // $result = file_get_contents($gateway);
        if ($result > 0) {
            $db = db();
            $sql = "INSERT INTO think_mobile (mobile,`code`,sendtime,validtime) VALUES ('$mobile',{$code},{$time},300) ON DUPLICATE KEY UPDATE sendtime={$time},code={$code}";
            $rs = $db->execute($sql);
             return ['code' => 1, 'msg' => '发送成功'];
             
        } else {
            return ['code' => 0, 'msg' => '发送失败'];
        }
        exit;

    }
}
